package com.bridgetree.jubaocrm.ui.project;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.util.BasicInfomationInterface;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Mmember;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.ui.LoginUtil;
/**
 *基本信息
 */
public class XMChildBasicInformationActivity extends Activity {
	private final String TAG ="XMChildBasicInformationActivity";
	private Context mContext;
	private ListView xm_bi_lv = null;
	private XMChildBasicInformationAdapter mXMChildBasicInformationAdapter = null;
//	private ArrayList<HashMap<String,Object>> proInfoListData = null;
	private Projects mProjects;
	private List<String> names;
	private TextView xm_bi_tv_title;
	private String user_id =""; 
	private String token ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_basic_information);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");

		}
		
		xm_bi_tv_title=(TextView)findViewById(R.id.xm_bi_tv_title);

		xm_bi_tv_title.setText(mProjects.getProject_name());
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		xm_bi_lv = (ListView)findViewById(R.id.xm_bi_lv);
		if(mProjects!=null){
			getBasicInfomation();
		}

		names =new ArrayList<String>();
		names.add("本项目于2014-04-21由刘德华创建，刘德华审批123456789");
		names.add("项目 名称");
		names.add("品牌");
		names.add("行业");
		names.add("营销状态");
		names.add("审核状态");
		names.add("锁定截止日期");
		names.add("销售人员");
		names.add("重要程度");
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	/**
	 * 获取基本信息
	 */
	private void getBasicInfomation() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			//			HashMap<String, String> mMap = new HashMap<String, String>();
			//			mMap.put("project_id", mProjects.getProject_id());
			//			mMap.put("user_id", mProjects.getUser_id());
			//			mMap.put("token", mProjects.getToken());
			//			mMap.put("part", "home");
			//			mMap.put("validation", CRMUserBaseInfo.kValication);
			//			String URL = "http://crmsoap.woniuwo.cn/project";
			String URL = Network.API_DOMAIN+"/project?project_id="+mProjects.getProject_id() +
			"&user_id="+user_id+"&token="+token+
			"&validation="+CRMUserBaseInfo.kValication+"&part=home";

			final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(  
					Request.Method.GET,   
					URL,   
					null,  
					new Response.Listener<JSONObject>() {  
						@Override  
						public void onResponse(JSONObject response) {  
							try {
								//							System.out.println("response="+response);  
								if (progressDialog.isShowing()&&progressDialog!=null) {  
									progressDialog.dismiss();  
								}  
								BasicInfomationInterface mBasicInfomationInterface =new BasicInfomationInterface();
								if (!response.isNull("project")) {
									String project = response.get("project").toString();
									Projects my_project = new Projects();
									JSONObject jsonObj2 = new JSONObject(project);
									if (!jsonObj2.isNull("trade")) {
										String trade = jsonObj2.getString("trade");
										my_project.setTrade(trade);
									}
									if (!jsonObj2.isNull("group_id")) {
										String group_id = jsonObj2.getString("group_id");
										my_project.setGroup_id(group_id);
									}
									if (!jsonObj2.isNull("created_user_fullname")) {
										String created_user_fullname = jsonObj2.getString("created_user_fullname");
										my_project.setCreated_user_fullname(created_user_fullname);
									}
									if (!jsonObj2.isNull("lock_end_date")) {
										String lock_end_date = jsonObj2.getString("lock_end_date");
										my_project.setLock_end_date(lock_end_date);
									}
									if (!jsonObj2.isNull("approved_by")) {
										String approved_by = jsonObj2.getString("approved_by");
										my_project.setApproved_by(approved_by);
									}
									if (!jsonObj2.isNull("created")) {
										String created = jsonObj2.getString("created");
										my_project.setCreated(created);
									}
									if (!jsonObj2.isNull("name")) {
										String name = jsonObj2.getString("name");
										my_project.setName(name);
									}
									if (!jsonObj2.isNull("project_name")) {
										String project_name = jsonObj2.getString("project_name");
										my_project.setProject_name(project_name);
									}
									if (!jsonObj2.isNull("import_level")) {
										String import_level = jsonObj2.getString("import_level");
										my_project.setImport_level(import_level);
									}
									if (!jsonObj2.isNull("project_id")) {
										String project_id = jsonObj2.getString("project_id");
										my_project.setProject_id(project_id);
									}
									if (!jsonObj2.isNull("process_status")) {
										String process_status = jsonObj2.getString("process_status");
										my_project.setProcess_status(process_status);
									}
									if (!jsonObj2.isNull("brand")) {
										String brand = jsonObj2.getString("brand");
										my_project.setBrand(brand);
									}
									if (!jsonObj2.isNull("approved_date")) {
										String approved_date = jsonObj2.getString("approved_date");
										my_project.setApproved_date(approved_date);
									}
									if (!jsonObj2.isNull("is_approved")) {
										boolean is_approved = Boolean.valueOf(jsonObj2.getString("is_approved"));
										my_project.setIs_approved(is_approved);
									}
									if (!jsonObj2.isNull("members")) {
										//									String project_id = jsonObj2.getString("members");
										org.json.JSONArray jsonArr;
										List<Mmember> members = new ArrayList<Mmember>();
										jsonArr = jsonObj2.getJSONArray("members");
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr.length(); i++) {
												Mmember mmember = new Mmember();
												JSONObject jsonObj3 = jsonArr.getJSONObject(i);
												if (!jsonObj3.isNull("user_id")) {
													String user_id = jsonObj3.getString("user_id");
													mmember.setUser_id(user_id);
												}
												if (!jsonObj3.isNull("fullname")) {
													String fullname = jsonObj3.getString("fullname");
													mmember.setFullname(fullname);
												}
												members.add(mmember);
											}
										}
										my_project.setMembers(members);
									}
									mBasicInfomationInterface.setProject(my_project);
								}
								if (!response.isNull("is_user_approve")) {
									boolean is_user_approve = Boolean.valueOf(response.get("is_user_approve").toString());
									mBasicInfomationInterface.setIs_user_approve(is_user_approve);
								}
								if (!response.isNull("is_edit_project")) {
									boolean is_edit_project = Boolean.valueOf(response.get("is_edit_project").toString());
									mBasicInfomationInterface.setIs_edit_project(is_edit_project);
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														openDailog("失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
											mBasicInfomationInterface.setErrors(mLoginError);
										}
									}
								}
								////over
								mXMChildBasicInformationAdapter = new XMChildBasicInformationAdapter(XMChildBasicInformationActivity.this,mBasicInfomationInterface.getProject(),names);
								xm_bi_lv.setAdapter(mXMChildBasicInformationAdapter);
								
								
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}  
					},   
					new Response.ErrorListener() {  
						@Override  
						public void onErrorResponse(VolleyError arg0) {  
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 
		}

	}

}

class XMChildBasicInformationAdapter extends BaseAdapter {
	private List<String> names;
	private Projects mProjects = null;
	private LayoutInflater listContainer; // 视图容器

	public final class ListItemView { // 自定义控件集合
		public TextView xm_12_item_title; 
		public TextView xm_12_item_content; 
	}

	public XMChildBasicInformationAdapter(Context mContext, Projects data,List<String> names) {
		this.mProjects = data;
		this.names = names;
		listContainer = (LayoutInflater) mContext
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		if (mProjects != null) {
			return 9;
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = null;
		if (convertView == null) {
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(R.layout.xm_basic_info_item, null);
			// 获取控件对象
			listItemView.xm_12_item_title = (TextView) convertView.findViewById(R.id.xm_12_item_title);
			listItemView.xm_12_item_content = (TextView) convertView.findViewById(R.id.xm_12_item_content);
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}
		// 设置文字和图片
//		names.add("本项目于2014-04-21由刘德华创建，刘德华审批123456789");
//		names.add("项目 名称");
//		names.add("品牌");
//		names.add("行业");
//		names.add("营销状态");
//		names.add("审核状态");
//		names.add("锁定截止日期");
//		names.add("销售人员");
//		names.add("重要程度");
		switch (position) {
		case 0:
			String info="本项目于"+mProjects.getCreated()+"由"+mProjects.getCreated_user_fullname()+"创建";
			if(mProjects.getApproved_by()==null || mProjects.getApproved_by().trim().length()==0 ){
				info+="， 目前正在组内审核中";
			}else{
				info+="，"+mProjects.getApproved_by()+"审批";
			}
			listItemView.xm_12_item_title.setText(info);
			listItemView.xm_12_item_content.setText("");
			break;
		case 1:
			listItemView.xm_12_item_title.setText(names.get(1));
			listItemView.xm_12_item_content.setText(mProjects.getName());
			break;
		case 2:
			listItemView.xm_12_item_title.setText(names.get(2));
			listItemView.xm_12_item_content.setText(mProjects.getBrand());
			break;
		case 3:
			listItemView.xm_12_item_title.setText(names.get(3));
			listItemView.xm_12_item_content.setText(mProjects.getTrade());
			break;
		case 4:
			listItemView.xm_12_item_title.setText(names.get(4));
			listItemView.xm_12_item_content.setText(mProjects.getProcess_status());
			break;
		case 5:
			listItemView.xm_12_item_title.setText(names.get(5));
			boolean is_approved = mProjects.getIs_approved();
			if(is_approved){
				listItemView.xm_12_item_content.setText(mProjects.getApproved_by()+"批准");
			}else{
				if(mProjects.getApproved_by()==null || mProjects.getApproved_by().trim().length()==0){
					listItemView.xm_12_item_content.setText("审核中");
				}else{
					listItemView.xm_12_item_content.setText(mProjects.getApproved_by()+"不批准");
				}
			}
			break;
		case 6:
			listItemView.xm_12_item_title.setText(names.get(6));
			listItemView.xm_12_item_content.setText(mProjects.getLock_end_date());
			break;
		case 7:
			listItemView.xm_12_item_title.setText(names.get(7));
			if(mProjects.getMembers().size()>0){
				listItemView.xm_12_item_content.setText(mProjects.getMembers().get(0).getFullname());
			}
			break;
		case 8:
			listItemView.xm_12_item_title.setText(names.get(8));
			listItemView.xm_12_item_content.setText(mProjects.getImport_level());
			break;
		}
		return convertView;
	}

}
